package org.summerframework.component.security.spring.filter;

import org.summerframework.component.security.context.RequestContextFactory;
import org.summerframework.component.security.spring.exception.UrlAuthenticationFailureHandler;
import org.summerframework.core.util.SpringContextUtil;
import org.summerframework.web.filter.BaseFilter;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 石超
 * @version v1.0.0
 */
public class RequestContextFilter implements BaseFilter {

    private final UrlAuthenticationFailureHandler urlAuthenticationFailureHandler;

    public RequestContextFilter(UrlAuthenticationFailureHandler urlAuthenticationFailureHandler) {
        this.urlAuthenticationFailureHandler = urlAuthenticationFailureHandler;
    }

    @Override
    public UrlAuthenticationFailureHandler getFilterFailureHandler() {
        return urlAuthenticationFailureHandler;
    }

    @Override
    public void onFilter(HttpServletRequest request, HttpServletResponse response) {
        String origin = request.getHeader("Origin");

        response.addHeader("Access-Control-Allow-Origin", StringUtils.isNotBlank(origin) ? origin : "*");
        response.addHeader("Access-Control-Allow-Credentials", "true");
        response.addHeader("Access-Control-Allow-Headers", "Accept,content-type,cache-control,x-requested-with,X_Requested_With,authorization,authentication,x-xsrf-token");
        response.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, OPTIONS");
        response.addHeader("Allow", "GET, POST, DELETE, PUT, OPTIONS");

        RequestContextFactory.initRequestContext(request, response, SpringContextUtil.getBean(ServletContext.class));
    }
}
